from ..models import User, db
from ..models import User
from werkzeug.security import check_password_hash
from datetime import datetime


def authenticate_user(username, password):
    user = User.query.filter_by(username=username).first()
    if user:
        # 尝试使用哈希密码验证
        if check_password_hash(user.password, password):
            return user

        # 如果哈希验证失败，尝试直接比较明文密码（不安全，仅限测试环境使用）
        if user.password == password:
            return user

    return None
def create_user(username, password, is_admin=False):
    new_user = User(username=username, password=password, is_admin=is_admin)
    db.session.add(new_user)
    db.session.commit()
    return new_user

def update_user(user_id, username=None, password=None, is_admin=None):
    user = User.query.get(user_id)
    if username is not None:
        user.username = username
    if password is not None:
        user.password = password
    if is_admin is not None:
        user.is_admin = is_admin
    db.session.commit()
    return user

def delete_user(user_id):
    user = User.query.get(user_id)
    db.session.delete(user)
    db.session.commit()


def reset_password_with_username_and_id(username, user_id, new_password):
    """
    根据用户名和用户ID重置密码（明文存储）
    :param username: 用户名
    :param user_id: 用户ID
    :param new_password: 新密码
    :return: 成功返回True，失败返回False
    """
    from datetime import datetime

    # 同时验证用户名和用户ID
    user = User.query.filter_by(username=username, id=user_id).first()
    if not user:
        return False

    try:
        # 直接存储明文密码（不安全！仅限内部测试使用）
        user.password = new_password
        user.updated_at = datetime.utcnow()
        db.session.commit()
        return True
    except Exception as e:
        db.session.rollback()
        print(f"密码重置失败: {str(e)}")
        return False
